import React from 'react'
import PropTypes from 'prop-types';
import { withStyles } from '@material-ui/core/styles'
import NormalDatePicker from '../DatePicker/NormalDatePicker'
import TextField from '@material-ui/core/TextField'
import Popover from '@material-ui/core/Popover'
import Fade from '@material-ui/core/Fade'
import Paper from '@material-ui/core/Paper'

const styles = theme => ({

})
const PROPS_BLACKLIST = [
    'onChange',
    'onClick',
    'parameters',
    'dateFormat'
];

const cleanProps = (props) => {
    PROPS_BLACKLIST.forEach(field => delete props[field]);
    return props;
};

class DateTextField extends React.Component  {

    state = {
        value: "",
        anchorEl: null
    }
    handleFocusText = event => {
        this.setState({anchorEl:event.currentTarget})
    }

    handleFocusClose = () => {
        this.setState({anchorEl: null})
    }

    activeDatePickerValue = (date) => {

        const { dateFormat } = this.props

        const value = date.Format(dateFormat)

        this.setState({anchorEl: null,value: value})

        this.props.onChange(value, ...this.props.parameters)

    }

    render(){

        const { ...props } = this.props;
        const { anchorEl,value } = this.state
        cleanProps(props);
        const open = Boolean(anchorEl);

        return (
            <React.Fragment>
                <TextField {...props} onClick={this.handleFocusText} value={value}>
                </TextField>
                <Popover id="simple-popper" open={open} anchorEl={anchorEl}  onClose={this.handleFocusClose}>
                    <Fade  timeout={250} in={true}>
                        <Paper>
                            <NormalDatePicker onSelect={ this.activeDatePickerValue }></NormalDatePicker>
                        </Paper>
                    </Fade>
                </Popover>
            </React.Fragment>
        )
    }
}
DateTextField.defaultProps = {
    dateFormat: 'yyyy-MM-dd'
}
DateTextField.propTypes = {
    onChange: PropTypes.func,
    parameters: PropTypes.array,
    dateFormat: PropTypes.string
}
export default withStyles(styles)(DateTextField)